<template>
  <el-row :gutter="10">
    <el-col>
      <el-card class="layout-query">
        <el-form ref="queryRef" :inline="true" :model="state.queryForm">
          <el-form-item label="" prop="velocity">
            <el-date-picker
              v-model="time"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              date-format="YYYY/MM/DD ddd"
              time-format="A hh:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              :default-value="time"
              :shortcuts="shortcuts"
              @change="getTime" />
          </el-form-item>
          <el-form-item label="选择设备" >
            <el-select
                v-model="state.queryForm.deviceIds"
                multiple
                clearable
                collapse-tags
                placeholder="请选择设备"
                popper-class="custom-header"
                :max-collapse-tags="1"
                style="width: 240px"
            >
              <template #header>
                <el-checkbox
                    v-model="checkAll"
                    :indeterminate="indeterminate"
                    @change="handleCheckAll"
                >
                  所有设备
                </el-checkbox>
              </template>
              <el-option v-for="item in DeviceList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="停留时长" prop="minParkDur">
            <el-select v-model="state.queryForm.minParkDur" placeholder="请选择" size="default" style="width: 240px">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button icon="Search" type="primary" @click="getdrivingList()">查询</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card>
        <!--        <el-space>-->
        <!--          <el-button v-auth="`statistics:trip_statistics:download`" plain icon="Download" @click="downloadExcel()"-->
        <!--            >导出</el-button-->
        <!--          >-->
        <!--        </el-space>-->
        <!--        </el-space>-->
        <el-table
          v-loading="dataListLoading"
          :data="data"
          border
          class="layout-table"
        >
          <el-table-column type="selection" header-align="center" align="center" width="50" />
          <el-table-column type="expand">
            <template #default="scope">
              <div >
                <el-table  :data="scope.row.stops" max-height="200">
<!--                  <el-table-column prop="imei" label="日期" header-align="center" align="center" />-->
                  <el-table-column prop="startTime" label="开始时间" header-align="center" align="center" />
                  <el-table-column prop="endTime" label="结束时间" header-align="center" align="center" />
                  <el-table-column label="停留时长" header-align="center" align="center">
                    <template #default="scope">
                      {{ timeFormat(timeToTimestamp(scope.row.endTime)-timeToTimestamp(scope.row.startTime))}}
                    </template>
                  </el-table-column>
<!--                  <el-table-column prop="" label="怠速时长" header-align="center" align="center" />-->
                  <el-table-column prop="distance" label="相隔里程" header-align="center" align="center">
                    <template #default="scope">
                      {{ mileageConversion(scope.row.distance )}}
                    </template>
                  </el-table-column>
                  <el-table-column prop="" label="区域" header-align="center" align="center" />
                  <el-table-column prop="address" label="地址" header-align="center" align="center" />
                </el-table>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="plateNo" label="设备名称" header-align="center" align="center" />
          <el-table-column prop="deviceid" label="设备序号" header-align="center" align="center" />
          <el-table-column prop="" label="停留时长" header-align="center" align="center">
            <template #default="scope">
              {{ timeFormat(timeToTimestamp(scope.row.endtime)-timeToTimestamp(scope.row.starttime))}}
            </template>
          </el-table-column>
          <el-table-column prop="occurTime" label="怠速时长" header-align="center" align="center" />
          <el-table-column prop="durationdistance" label="里程" header-align="center" align="center">
            <template #default="scope">
              {{ mileageConversion(scope.row.durationdistance )}}
            </template>
          </el-table-column>
<!--          <el-table-column prop="" label="油耗" header-align="center" align="center" />-->
<!--          <el-table-column prop="occurTime" label="所属账号" header-align="center" align="center" />-->
<!--          <el-table-column prop="endTime" label="分组名称" header-align="center" align="center" />-->
        </el-table>
<!--        <el-pagination-->
<!--          :current-page="state.page"-->
<!--          :page-sizes="state.pageSizes"-->
<!--          :page-size="state.limit"-->
<!--          :total="state.total"-->
<!--          layout="total, sizes, prev, pager, next"-->
<!--          @size-change="sizeChangeHandle"-->
<!--          @current-change="currentChangeHandle">-->
<!--        </el-pagination>-->
      </el-card>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { useCrud } from '@/hooks'
import { reactive, ref, watch } from 'vue'
import { IHooksOptions } from '@/hooks/interface'
import OrgTree from '@/views/sys/user/org-tree.vue'
import Detail from '@/views/biz/waybill/detail.vue'
import { useRouter } from 'vue-router'
import MaDictColumn from '@/components/ma-dict/ma-dict-column/index.vue'

import { CheckboxValueType, ElMessage, ElMessageBox } from 'element-plus'
import moment from 'moment'
import { useDeviceListApi } from '@/api/gps/device'
import { getdrivingListApi } from '@/api/statistics/driving'
import {mileageConversion, timeFormat} from '@/utils/gps/format'
const queryRef = ref()
const dataListLoading = ref(false)
const data = ref()
const state: IHooksOptions = reactive({
  // dataListUrl: '/gps/alarm/allAlarms',
  // newParams: true,
  // deleteUrl: '/biz/waybill',
  // responseInterceptor: (data) => {
  //   data?.forEach((value, index) => {
  //     data[index].haveAlarm = value.haveAlarm.toString()
  //   })
  //   return data
  // },
  queryForm: {
    startTime: `${moment().format('YYYY-MM-DD')} 00:00:00`,
    endTime: `${moment().format('YYYY-MM-DD')} 23:59:59`,
    minParkDur: '5',
    withStop: true,
    deviceIds: []
  }
})
const options = [
  {
    value: '5',
    label: '5分钟'
  },
  {
    value: '15',
    label: '15分钟'
  },
  {
    value: '30',
    label: '30分钟'
  },
  {
    value: '60',
    label: '1小时'
  },
  {
    value: '120',
    label: '2小时'
  }
]
function getdrivingList() {
  if (state.queryForm.deviceIds.length === 0) {
    ElMessage.error({
      message: '请选择设备',
      duration: 500
    })
    return
  }
  dataListLoading.value = true
  getdrivingListApi(state.queryForm).then((res) => {
    dataListLoading.value = false
    data.value = res.data
  })
}

//时间转时间戳
// 北京时间：2021-11-18 22:14:24
/* 时间yyyy-MM-dd HH:mm:ss转为时间戳 */
function timeToTimestamp(time){
  let timestamp = Date.parse(new Date(time).toString());
  //timestamp = timestamp / 1000; //时间戳为13位需除1000，时间戳为13位的话不需除1000
  // console.log(time + "的时间戳为：" + timestamp);
  return timestamp;
  //2021-11-18 22:14:24的时间戳为：1637244864707
}



const downloadExcel = () => {
  downloadHandle('/biz/car/exportall').then(() => {
    ElMessage.success({
      message: '操作成功',
      duration: 500
    })
  })
}
// const mineList = ref<any[]>([])
const time = ref([state.queryForm.startTime, state.queryForm.endTime])
const DeviceList = ref([])
const checkAll = ref(false)
const indeterminate = ref(false)
function useDeviceList() {
  useDeviceListApi({
    orderField: 'signal_update_time',
    onlyVideo: false,
    order: 'DESC',
    pageNum: 1,
    pageSize: 1000,
    keyWords: ''
  }).then((res) => {
    DeviceList.value = res.data.list.map((res) => {
      return {
        value: res.imei,
        label: res.plateNo + ' ——' + res.subTitle
      }
    })
  })
}
useDeviceList()

watch(state.queryForm.devicelds, (val) => {
  if (val.length === 0) {
    checkAll.value = false
    indeterminate.value = false
  } else if (val.length === DeviceList.value.length) {
    checkAll.value = true
    indeterminate.value = false
  } else {
    indeterminate.value = true
  }
})

const handleCheckAll = (val: CheckboxValueType) => {
  indeterminate.value = false
  if (val) {
    state.queryForm.deviceIds = DeviceList.value.map((_) => _.value)
  } else {
    state.queryForm.deviceIds = []
  }
}

function getTime(e) {
  if (e === null) {
    state.queryForm.endTime = ''
    state.queryForm.startTime = ''
  } else {
    if (e[0] === e[1]) {
      state.queryForm.startTime = e[0]
      const a = e[1].split(' ')
      state.queryForm.endTime = a[0] + ' 23:59:59'
      return
    }
    state.queryForm.startTime = e[0]
    state.queryForm.endTime = e[1]
  }
}

const shortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setDate(start.getDate() - 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 1)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 3)
      return [start, end]
    }
  }
]
const handleOrgClick = (orgId: any) => {
  state.queryForm.sysOrgId = orgId
  getDataList()
}

const {
  getDataList,
  selectionChangeHandle,
  sizeChangeHandle,
  currentChangeHandle,
  deleteBatchHandle,
  reset,
  downloadHandle
} = useCrud(state)
</script>
<style>
.hide {
  width: 200px;
  overflow: hidden;
  word-wrap: break-word;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
}
</style>
